package com.bbs.core.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bbs.core.model.User;
import com.bbs.core.service.UserService;
import com.bbs.core.dao.UserDao;
import com.github.pagehelper.PageHelper;

/**
 * Created by Administrator on 2017/8/16.
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;//这里会报错，但是并不会影响

    /*
    * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
    * 很简单，只需要在service层传入参数，然后将参数传递给一个插件的一个静态方法即可；
    * pageNum 开始页数
    * pageSize 每页显示的数据条数
    * */
    @Override
    public List<User> findUsersByPage(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了，非常简单。
        PageHelper.startPage(pageNum, pageSize);
        return userDao.selectAllUsers();
    }

	
	/**
	 * 分5个级别
	 * @param score
	 * @return
	 */
	private int getLevel(int score){
		if(score>=UserService.PRESIDENT_THRESHOLD){
			return 5;
		}else if(score>=UserService.DIRECTOR_THRESHOLD){
			return 4;
		}else if(score>=UserService.TEACHER_THRESHOLD){
			return 3;
		}if(score>=UserService.OLD_THRESHOLD){
			return 2;
		}else{
			return 1 ;
		}
	}




	@Override
	public User setUserAccount(User user){
		userDao.insertUser(user);
		return user;
		
	}

	@Override
	public User getUserAccount(String userName, String password) {
		User query = new User();
		query.setUserName(userName);
		query.setPassword(password);
		User user= userDao.selectUserByNameAndPassword(query);
		return user;
	}


	@Override
	public void addTopicScore(int userId) {
		addScore(userId,UserService.BBS_TOPIC_SCORE);
		
	}

	@Override
	public void addPostScore(int userId) {
		addScore(userId,UserService.BBS_POST_SCORE);
		
	}

	@Override
	public void addReplayScore(int userId) {
		addScore(userId,UserService.BBS_REPLAY_SCORE);
		
	}
	
	private void addScore(int userId,int total){
		User user = userDao.selectUserByPrimaryKey(new Integer(userId));
		int score = user.getScore()+total;
		int balance = user.getBalance()+total;
		user.setScore(score);
		user.setBalance(balance);
		user.setLevel(getLevel(score));
		userDao.updateUserByPrimaryKey(user);
	}




	@Override
	public boolean hasUser(String userName) {
		User user = new User();
		user.setUserName(userName);
		User userFind = userDao.selectUserByName(user);
		if(userFind !=null){
			return true;
		}else{
			return false;
		}
	}
	
	@Override
	public void saveUser(User user) {
		userDao.insertUser(user);
	}

	@Override
	public User login(User user) {
		return userDao.selectUserByNameAndPassword(user);
	}

	@Override
	public User selectByPrimaryKey(Integer id) {
		return userDao.selectUserByPrimaryKey(id);
	}

}
